﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.IO;
using DNA.Utility;

namespace DNA.Mvc.Installation
{
    public class WebTemplateInstaller : InstallerBase
    {
        private IDataContext DbContext = null;

        public WebTemplateInstaller(IDataContext dataContext)
        {
            DbContext = dataContext;
        }

        public override string Name
        {
            get
            {
                return "webs";
            }
        }

        public override void Execute(InstallationContext context)
        {
            var config = GetConfig<WebTemplateConfiguration>();
            if (!string.IsNullOrEmpty(config.Template))
            {
                string tmplFile = ExecutionPath + "\\" + config.Template;

                if (!File.Exists(tmplFile)) throw new Exception("Template file not exists");

                string tmplContent = File.ReadAllText(tmplFile);

                if (config.Replacements != null)
                {
                    foreach (var match in config.Replacements)
                    {
                        if (context.Data.ContainsKey(match.Value))
                        {
                            var _val = context.Data[match.Value] as string;
                            if (!string.IsNullOrEmpty(_val))
                                tmplContent = tmplContent.Replace(match.Match, _val);
                        }
                    }
                }
                var webTmpl = XmlSerializerUtility.DeserializeFromXmlText<WebTemplate>(tmplContent);

                if (webTmpl == null)
                    throw new Exception("Serializer error.Could not load the Web template file.");

                string name = context.Data["Web.Name"].ToString();
                string owner = context.Data["Web.Owner"].ToString();

                var newWeb = DbContext.Import(webTmpl, name, owner);

            }
        }
    }
}
